<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/11/27
 * Time: 12:21
 */
namespace app\appmenu\controller;

use app\appmenu\config\appmenu_config;
use app\common\config\weixin_config;
use app\common\helper\appmenu_helper;
use app\common\helper\setting_helper;
use app\common\model\Appmenu;
use app\common\model\Company;
use app\common\model\OpenCard;
use app\common\model\Setting;
use think\facade\View;
use think\facade\Request;
use app\admin\controller\AdminBase;

class SyncMenu extends AdminBase
{
    protected $appmenu_key = array();

    public function initialize()
    {
        parent::initialize();
        $this->open_card_id = OpenCard::get_open_card_id();
        $this->company_id   = Company::get_company_id();
        $appmenu_key        = Setting::get_setting_info('appmenu_key');
        if ($appmenu_key) {
            $this->appmenu_key = unserialize($appmenu_key);
        }
    }

    /**
     * 同步菜单
     */
    public function sync()
    {
        //return '服务号菜单申请中....';
        $access_token = $this->appmenu_key['access_token'];
        $appid        = $this->appmenu_key['appid'];
        $serect       = $this->appmenu_key['appsecret'];

        $store_id = Request::param('store_id', $this->open_card_id);
        $store_id = $store_id == 0 ? $this->open_card_id : $store_id;

        $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$serect;
        // 如果$access_token不存在, 则请求接口
        if (!$access_token) {
            $access_token = appmenu_helper::get_access_token($token_url);
            if (!$access_token) {
                return ['info' => '获取凭证失败，请检查授权信息'];
            }
        }

        $data = '{ "button":[ ';
        $menu_list = appmenu_helper::get_menu_list_for_weixin(0, $store_id);
        if (!$menu_list) {
            return ['info' =>'菜单信息为空，不能同步'];
        }


        //@example key值为：V{$menu_id}_C_{$type}_{$appmsg_id}
        foreach ($menu_list as $k=>$v) {
            if (!isset($v['son_list']) || !$v['son_list']) {
                if (!$v['content']) {
                    return '父菜单:“'.$v['title'].'”设置不完整，请设置它的回复方式';
                }
                if ($v['type'] == 60) {
                    $mini_data = explode(appmenu_config::$miniprogram_devide, $v['content']);
                    if (count($mini_data) != 3) {
                        return $v['title'].'菜单设置信息不全';
                    }
                    $data .= '{"type":"'.appmenu_config::$menu_type[$v['type']].'","name":"'.$v['title'].'","'.appmenu_config::$menu_show[$v['type']].'":"'.appmenu_helper::menu_details_key($v['id'], $v['type'], $mini_data[2]).'","appid":"'.$mini_data[0].'","pagepath":"'.$mini_data[1].'"}';
                } else {
                    $data .= '{"type":"'.appmenu_config::$menu_type[$v['type']].'","name":"'.$v['title'].'","'.appmenu_config::$menu_show[$v['type']].'":"'.appmenu_helper::menu_details_key($v['id'], $v['type'], $v['content']).'"}';
                }

                if (isset($menu_list[$k+1])) {
                    $data .= ',';
                }
            } else {
                $data .= '{"name":"'.$v['title'].'","sub_button":[';
                foreach ($v['son_list'] as $k1=>$v1) {
                    // 未设置完菜单
                    if (!$v1['content']) {
                        return '子菜单:“'.$v1['title'].'”设置不完整，请设置它的回复方式';
                    }

                    if ($v1['type'] == 60) {
                        $mini_data = explode(appmenu_config::$miniprogram_devide, $v1['content']);
                        if (count($mini_data) != 3) {
                            return $v1['title'].'菜单设置信息不全';
                        }
                        $data .= '{"type":"'.appmenu_config::$menu_type[$v1['type']].'","name":"'.$v1['title'].'","'.appmenu_config::$menu_show[$v1['type']].'":"'.appmenu_helper::menu_details_key($v1['id'], $v1['type'], $mini_data[2]).'","appid":"'.$mini_data[0].'","pagepath":"'.$mini_data[1].'"}';
                    } else {
                        $data .= '{"type":"'.appmenu_config::$menu_type[$v1['type']].'","name":"'.$v1['title'].'","'.appmenu_config::$menu_show[$v1['type']].'":"'.appmenu_helper::menu_details_key($v1['id'], $v1['type'], $v1['content']).'"}';
                    }
                    if (isset($v['son_list'][$k1+1])) {
                        $data .= ',';
                    }
                }
                $data .= ']}';
                if (isset($menu_list[$k+1])) {
                    $data .= ',';
                }
            }
        }

        $menu_store_id = $menu_list[0]['store_id'];
//        if ($menu_store_id == 0) {
            $data .= ']}';

            //echo($data);exit;

            $url_menu = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
            $menu_res = curl($url_menu, "POST", $data);
            //@TODO 具体的返回值待测 如果不返回ok 则有可能是access_token过期 再次获取access_token
            if ($menu_res->errmsg != "ok") {
                $access_token = appmenu_helper::get_access_token($token_url);
                $this->appmenu_key['access_token'] = $access_token;
                setting_helper::update_setting_info('appmenu_key', serialize($this->appmenu_key));
                //$url_del = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$access_token;
                //curl($url_del);

                $url_menu = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
                $menu_res = curl($url_menu, "POST", $data);
            }
            if ($menu_res->errmsg != "ok") {
                if (array_key_exists($menu_res->errcode, weixin_config::$err_code)) {
                    return ['info' =>  weixin_config::$err_code[$menu_res->errcode]];
                }

                return ['info' => '同步失败 '.$menu_res->errmsg.'['.$menu_res->errcode.']'];
            }

//        } else {
//            $menu_store_info = get_res_info('store', $menu_store_id);
//            if (!$menu_store_info) {
//                return '该店铺不存在';
//            }
//            if (!$menu_store_info['tag_id']) {
//                return '该店铺尚无标签，不能自定义菜单';
//            }
//
//            $tag_id = $menu_store_info['tag_id'];
//
//            $data .= '],';
//            $data .= '"matchrule":{"tag_id":"'.$tag_id.'"}}';
//            //var_dump($data);exit;
//            $url_menu = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=".$access_token;
//            $menu_res = h_curl($url_menu, $data, 1);
//            //var_dump($menu_res);
//            //@TODO 具体的返回值待测 如果不返回ok 则有可能是access_token过期 再次获取access_token
//            if (!isset($menu_res['menuid'])) {
//                $access_token = appmenu_helper::get_access_token($token_url);
//                $this->appmenu_key['access_token'] = $access_token;
//                setting_helper::update_setting_info('appmenu_key', serialize($this->appmenu_key));
//                //$url_del = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$access_token;
//                //curl($url_del);
//
//                $url_menu = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=".$access_token;
//                $menu_res = h_curl($url_menu, $data, 1);
//            }
//            if (!isset($menu_res['menuid'])) {
//                if (array_key_exists($menu_res['errcode'], weixin_config::$err_code)) {
//                    return weixin_config::$err_code[$menu_res['errcode']];
//                }
//
//                return '同步失败 '.$menu_res['errmsg'].'['.$menu_res['errcode'].']';
//            }
//
//            // 添加wxmenuid，清除该菜单时有用
//            appmenu_helper::add_appmenu_store($menu_store_id, $menu_res['menuid']);
//
//            return array('info'=>'ok', 'menuid'=>$menu_res);
//        }

        //var_dump($data);exit;



        return ['info' => 'ok'];
    }

    /**
     * 清空菜单
     */
    public function clear()
    {
        //return '服务号菜单申请中....';
        $access_token = $this->appmenu_key['access_token'];
        $appid        = $this->appmenu_key['appid'];
        $serect       = $this->appmenu_key['appsecret'];

        $url_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$serect;
        // 如果$access_token不存在, 则请求接口
        if (!$access_token) {
            //$access_token = appmenu_helper::get_access_token($url_token);
            //if (!$access_token) {
            return '获取凭证失败，请检查授权信息';
            //}
        }

        $url_del = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$access_token;
        $menu_res = curl($url_del);
        if ($menu_res->errmsg != "ok") {
            return '系统繁忙,稍后再试';
        }

        return ['info' => 'ok'];
    }

}